import arrowIcon from "@/assets/images/icon_jump.png";
import PageContainer from "@/components/PageContainer";
import { useDeviceShare } from "@/hooks";
import useEvent from "@/hooks/useEvent";
import useInputState from "@/hooks/useInputState";
import { updateDeviceShareRecord } from "@/services/share";
import { DynamicColors, GDynamicValue, GStyleSheet } from "@/utils/DarkMode";
import { Input } from "@taroify/core";
import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useRouter, useShareAppMessage } from "@tarojs/taro";
import i18n from "i18n-js";
import moment from "moment";
import React, { useEffect, useMemo, useState, useCallback } from "react";
// import lineIcon from "../images/link.png";
import phoneIcon from "../images/phone.png";
import qrcodeIcon from "../images/qrcode.png";
import wechatIcon from "../images/wechat.png";

const dstyles = GStyleSheet.create({
  container: {
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
  },
  header: {
    height: 48,
    display: 'flex',
    alignItems: 'center',
    padding: '0 30rpx',
  },
  content: {
    flex: 1,
    background: '#fff',
  },
  mode: {
    height: 58,
    margin: '0 30rpx',
    display: 'flex',
    alignItems: 'center',
    borderTop: 1,
    borderTopColor: '#F0F0F0',
    borderTopStyle: 'solid',
    position: 'relative'
  },
  circle: {
    width: 32,
    height: 32,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: 10,
    borderRadius: '50%',
  },
  icon: {
    width: 16,
    height: 16,
  },
  label: {
    flex: 1,
    fontSize: 16,
  },
  arrow: {
    tintColor: new GDynamicValue("#888", "#ccc"),
    marginLeft: 10,
    width: 16,
    height: 16,
  },
  copy: {
    fontSize: 16,
    color: DynamicColors.tintColor,
  },
  shareButton: {
    position: 'absolute',
    left: -15,
    right: -15,
    bottom: 0,
    top: 0,
    opacity: 0.00000000001, // 不知道为啥，如果 opacity 是 0，则会被去掉
  },
  limit: {
    display: 'flex',
    background: '#fff',
    alignItems: 'center',
    paddingLeft: 15,
    paddingRight: 15,
    height: 58,
  },
  limitText: {
    flex: 1,
  },
  limitRight: {
    display: 'flex',
    alignItems: 'center',
  },
  limitInput: {
    border: '1rpx solid #000',
    borderRadius: 4,
    textAlign: 'center',
    width: 70,
    height: 36,
    fontSize: 16,
    marginRight: 10,
  },
});

interface IMode {
  id: string;
  label: string;
  bgColor: string;
  icon: string;
  arrow?: boolean;
  extra?: any;
  disabled?: boolean;
  onPress(): void;
}

const Mode: React.FC<IMode> = React.memo(({
  id,
  label,
  bgColor,
  icon,
  arrow,
  extra,
  disabled,
  onPress
}) => {
  const styles = dstyles.useDynamicStyle();

  return (
    <View style={styles.mode} onClick={onPress}>
      <View style={{ ...styles.circle, background: bgColor }}>
        <Image src={icon} style={styles.icon} />
      </View>
      <Text style={styles.label}>{label}</Text>
      {!!extra && (extra)}
      {arrow && (
        <Image src={arrowIcon} style={styles.arrow} />
      )}
      {
        id === 'wechat' && (
          <Button disabled={disabled} style={styles.shareButton} openType='share' />
        )
      }
    </View>
  );
});

type Params = {
  shareId: string;
} | {
  mac: string;
  productKey: string;
}

const ShareModes = () => {
  const styles = dstyles.useDynamicStyle();
  const deviceShare = useDeviceShare();
  const formatter = useEvent((value: string) => {
    const limit = parseInt(value, 10);
    return Number.isNaN(limit) ? '' : Math.abs(limit).toString();
  });
  const [limitText, changeLimitText, setLimitText] = useInputState('1', formatter);
  const numberLimit = useMemo(() => limitText ? parseInt(limitText, 10) : 1, [limitText]);

  const router = useRouter<Params>();

  const [shareId, setShareId] = useState('shareId' in router.params ? router.params.shareId : '');

  useEffect(() => {
    if ('shareId' in router.params) {
      return;
    }
    Taro.showLoading();
    deviceShare.setSelectedDevices([router.params as IDevice]);
    deviceShare.createDeviceShareRecord().then((res) => {
      if (res.success && res.data) {
        setShareId(res.data);
      }
    }).finally(() => Taro.hideLoading())
  }, []);

  const handleQRCode = useEvent(async () => {
    const expiryTime = moment().add(1, 'days').format('YYYY-MM-DD HH:mm:ss')
    const res = await deviceShare.createDeviceShareRecord({ numberLimit, expiryTime });
    if (!res.success || !res.data) {
      return;
    }
    Taro.navigateTo({ url: `/pages/share/qrcode/index?shareId=${res.data}&expiryTime=${expiryTime}`, })
  });

  const handleWeChat = useEvent(() => {
    console.log('WeChat Share');
    updateDeviceShareRecord({ code: shareId, numberLimit, expiryDays: 15 });
  });
  
  const handlePhone = useCallback(() => {
    Taro.navigateTo({ url: '/pages/share/account/index', })
  }, []);
  // const handleLink = useCallback(() => { }, []);

  const onBlur = useEvent(() => {
    if (!limitText || limitText === '0') {
      setLimitText('1');
    }
  })

  useShareAppMessage(res => {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '设备分享',
      path: `/pages/home/index?shareId=${shareId}`,
      imageUrl: 'https://xbgroup-static.gizwits.com/cybertron/users/391941/media/%E7%BC%96%E7%BB%84@3x_1734329802977.png'
    }
  })

  const modes: IMode[] = useMemo(() => [
    {
      id: 'qrcode',
      label: i18n.t('QRCODE_SHARE'),
      icon: qrcodeIcon,
      bgColor: '#4587E8',
      arrow: true,
      onPress: handleQRCode,
    },
    {
      id: 'wechat',
      label: i18n.t('WECHAT_FRIEND'),
      icon: wechatIcon,
      bgColor: '#08D43F',
      arrow: true,
      disabled: !shareId,
      onPress: handleWeChat,
    },
    {
      id: 'phone',
      label: i18n.t('ACCOUNT_SHARE'),
      icon: phoneIcon,
      bgColor: '#F2B928',
      arrow: true,
      onPress: handlePhone,
    },
    // {
    //   id: 'link',
    //   label: I18n.t('COPY_SHARE_LINK'),
    //   icon: lineIcon,
    //   bgColor: '#E07D1B',
    //   extra: (<Text style={styles.copy}>{I18n.t('COPY')}</Text>),
    //   onPress: handleLink,
    // },
  ], [shareId, handleQRCode, handleWeChat, handlePhone]);

  return (
    <PageContainer title={i18n.t('DEVICE_SHARED_MANAGE')}>
      <View style={styles.container}>
        <View style={styles.header}>
          {i18n.t('SELECT_SHARE_MODE')}
        </View>
        <View style={styles.limit}>
          <Text style={styles.limitText}>{i18n.t('PERMIT_SHARE')}</Text>
          <View style={styles.limitRight}>
            <Input
              style={styles.limitInput}
              type='number'
              value={limitText}
              onBlur={onBlur}
              onChange={changeLimitText}
            />
            <Text>{i18n.t('PERSON')}</Text>
          </View>
        </View>
        <View style={styles.content}>
          {modes.map(m => (
            <Mode key={m.id} {...m} />
          ))}
        </View>
      </View>
    </PageContainer>
  );
}

export default ShareModes;
